/*
 * Copyright:  2018 smarabbit studio.
 *
 * Licensed under the Confluent Community License; you may not use this file except in
 * compliance with the License.  You may obtain a copy of the License at
 *
 * http://www.confluent.io/confluent-community-license
 *
 *  Unless required by applicable law or agreed to in writing, software distributed under
 *  the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 *  either express or implied.  See the License for the specific language governing
 *  permissions and limitations under the License.
 *
 *  @作   者： 黄开晖 (117227773@qq.com)
 *  @日   期:    2020/7/27 上午9:51
 *
 */

package com.massyframework.beanskin.springboot.beancontext;

import java.util.Objects;

import org.springframework.boot.Banner;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;
import org.springframework.context.ApplicationContextInitializer;
import org.springframework.core.io.DefaultResourceLoader;
import org.springframework.web.context.support.AbstractRefreshableWebApplicationContext;

import com.massyframework.beanskin.assembly.Assembly;

/**
 * {@link AssemblyServletInitializer}, 装配件Servlet初始化器
 */
public class AssemblyServletInitializer extends SpringBootServletInitializer {

    private Assembly assembly;
    private Class<?>[] annoTypes;
    private ApplicationContextInitializer<AbstractRefreshableWebApplicationContext> initializer;

    public AssemblyServletInitializer(Assembly assembly,
                                      Class<?>[] annoTypes,
                                      ApplicationContextInitializer<AbstractRefreshableWebApplicationContext> initializer) {
        this.assembly = Objects.requireNonNull(assembly, "\"assembly\" cannot be null.");
        this.initializer = initializer;
        this.annoTypes = annoTypes;
    }

    /**
     * Configure the application. Normally all you would need to do is to add sources
     * (e.g. config classes) because other settings have sensible defaults. You might
     * choose (for instance) to add default command line arguments, or set an active
     * Spring profile.
     *
     * @param builder a builder for the application context
     * @return the application builder
     * @see SpringApplicationBuilder
     */
    @Override
    protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) {
        builder.bannerMode(Banner.Mode.OFF)
                .sources(annoTypes);
        if (this.initializer != null){
            builder.initializers(this.initializer);
        }

        DefaultResourceLoader resourceLoader = new DefaultResourceLoader(assembly.getModuleClassLoader());
        builder.resourceLoader(resourceLoader);
        return super.configure(builder);
    }
}
